<template>
	<view class="user-info-container">
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<text class="title">个人信息</text>
			<view class="edit-btn" @click="toggleEditMode">
				<text class="edit-text">{{ isEditing ? '保存' : '编辑' }}</text>
			</view>
		</view>
		
		<view class="content">
			<!-- 头像上传区域 -->
			<view class="avatar-section">
				<AvatarUpload 
					:avatar="userInfo.avatar"
					:gender="userInfo.gender"
					:disabled="!isEditing"
					@avatar-changed="onAvatarChanged"
				/>
				<text class="avatar-tip">点击头像可更换</text>
			</view>
			
			<view class="info-section">
				<view class="info-item">
					<text class="label">用户名</text>
					<text class="value">{{ userInfo.username }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">昵称</text>
					<input 
						v-if="isEditing" 
						class="input-field" 
						v-model="formData.nickname" 
						placeholder="请输入昵称"
						:disabled="!isEditing"
					/>
					<text v-else class="value">{{ userInfo.nickname || '未设置' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">邮箱</text>
					<input 
						v-if="isEditing" 
						class="input-field" 
						v-model="formData.email" 
						placeholder="请输入邮箱"
						type="email"
						:disabled="!isEditing"
					/>
					<text v-else class="value">{{ userInfo.email || '未设置' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">手机号</text>
					<input 
						v-if="isEditing" 
						class="input-field" 
						v-model="formData.phone" 
						placeholder="请输入手机号"
						type="number"
						maxlength="11"
						:disabled="!isEditing"
					/>
					<text v-else class="value">{{ userInfo.phone || '未设置' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">性别</text>
					<picker 
						v-if="isEditing" 
						:value="formData.gender - 1" 
						:range="genderOptions" 
						@change="onGenderChange"
						class="picker-field"
					>
						<view class="picker-text">{{ genderOptions[formData.gender - 1] || '请选择性别' }}</view>
					</picker>
					<text v-else class="value">{{ getGenderText(userInfo.gender) }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">生日</text>
					<picker 
						v-if="isEditing" 
						mode="date" 
						:value="formData.birthDate" 
						@change="onBirthdayChange"
						class="picker-field"
					>
						<view class="picker-text">{{ formData.birthDate || '请选择生日' }}</view>
					</picker>
					<text v-else class="value">{{ userInfo.birthDate || '未设置' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">地址</text>
					<input 
						v-if="isEditing" 
						class="input-field" 
						v-model="formData.address" 
						placeholder="请输入地址"
						:disabled="!isEditing"
					/>
					<text v-else class="value">{{ userInfo.address || '未设置' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">注册时间</text>
					<text class="value">{{ formatDate(userInfo.createTime) }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">最后登录</text>
					<text class="value">{{ formatDate(userInfo.lastLoginTime) }}</text>
				</view>
			</view>
		</view>
		
		<!-- 编辑模式下的操作按钮 -->
		<view v-if="isEditing" class="action-buttons">
			<button class="cancel-btn" @click="cancelEdit">取消</button>
			<button class="save-btn" @click="saveUserInfo" :disabled="saving">保存</button>
		</view>
	</view>
</template>

<script>
import AvatarUpload from '../../components/AvatarUpload.vue';

export default {
	components: {
		AvatarUpload
	},
	data() {
		return {
			userInfo: {},
			isEditing: false,
			saving: false,
			formData: {
				nickname: '',
				email: '',
				phone: '',
				gender: 1,
				birthDate: '',
				address: ''
			},
			genderOptions: ['男', '女'],
			originalData: {} // 保存原始数据，用于取消编辑
		}
	},
	
	onLoad() {
		this.loadUserInfo();
	},
	
	methods: {
		// 加载用户信息
		async loadUserInfo() {
			try {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || !userInfo.id) {
					uni.showToast({
						title: '用户信息不存在',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
					return;
				}
				
				// 从服务器获取最新的用户信息
				const response = await uni.request({
					url: `http://localhost:8080/user-manage/profile?userId=${userInfo.id}`,
					method: 'GET',
					header: {
						'Authorization': `Bearer ${uni.getStorageSync('token')}`
					}
				});
				
				if (response.data.code === 200) {
					this.userInfo = response.data.data;
					this.initFormData();
				} else {
					uni.showToast({
						title: response.data.message || '获取用户信息失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载用户信息失败:', error);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			}
		},
		
		// 初始化表单数据
		initFormData() {
			this.formData = {
				nickname: this.userInfo.nickname || '',
				email: this.userInfo.email || '',
				phone: this.userInfo.phone || '',
				gender: this.userInfo.gender || 1,
				birthDate: this.userInfo.birthDate || '',
				address: this.userInfo.address || ''
			};
			// 保存原始数据
			this.originalData = { ...this.formData };
		},
		
		// 切换编辑模式
		toggleEditMode() {
			if (this.isEditing) {
				this.saveUserInfo();
			} else {
				this.isEditing = true;
			}
		},
		
		// 取消编辑
		cancelEdit() {
			this.isEditing = false;
			this.formData = { ...this.originalData };
		},
		
		// 保存用户信息
		async saveUserInfo() {
			if (!this.validateForm()) {
				return;
			}
			
			this.saving = true;
			
			try {
				const requestData = {
					id: this.userInfo.id,
					...this.formData
				};
				
				const response = await uni.request({
					url: 'http://localhost:8080/user-manage/profile/update',
					method: 'PUT',
					data: requestData,
					header: {
						'Content-Type': 'application/json',
						'Authorization': `Bearer ${uni.getStorageSync('token')}`
					}
				});
				
				if (response.data.code === 200) {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
					
					// 更新本地用户信息
					this.userInfo = { ...this.userInfo, ...this.formData };
					uni.setStorageSync('userInfo', this.userInfo);
					
					// 保存原始数据
					this.originalData = { ...this.formData };
					
					this.isEditing = false;
				} else {
					uni.showToast({
						title: response.data.message || '保存失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('保存用户信息失败:', error);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.saving = false;
			}
		},
		
		// 验证表单
		validateForm() {
			if (this.formData.email && !this.isValidEmail(this.formData.email)) {
				uni.showToast({
					title: '请输入正确的邮箱格式',
					icon: 'none'
				});
				return false;
			}
			
			if (this.formData.phone && !this.isValidPhone(this.formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号格式',
					icon: 'none'
				});
				return false;
			}
			
			return true;
		},
		
		// 验证邮箱格式
		isValidEmail(email) {
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			return emailRegex.test(email);
		},
		
		// 验证手机号格式
		isValidPhone(phone) {
			const phoneRegex = /^1[3-9]\d{9}$/;
			return phoneRegex.test(phone);
		},
		
		// 性别选择器变化
		onGenderChange(e) {
			this.formData.gender = parseInt(e.detail.value) + 1;
		},
		
		// 生日选择器变化
		onBirthdayChange(e) {
			this.formData.birthDate = e.detail.value;
		},
		
		// 获取性别文本
		getGenderText(gender) {
			if (gender === 1) return '男';
			if (gender === 2) return '女';
			return '未设置';
		},
		
		// 格式化日期
		formatDate(dateStr) {
			if (!dateStr) return '未设置';
			// 处理LocalDate格式 (YYYY-MM-DD)
			if (typeof dateStr === 'string' && dateStr.includes('-')) {
				const [year, month, day] = dateStr.split('-');
				return `${year}年${month}月${day}日`;
			}
			// 处理其他日期格式
			const date = new Date(dateStr);
			return date.toLocaleDateString('zh-CN');
		},
		
		// 头像变更处理
		onAvatarChanged(filePath) {
			this.userInfo.avatar = filePath;
			// 更新本地存储
			uni.setStorageSync('userInfo', this.userInfo);
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack();
		}
	}
}
</script>

<style scoped>
.user-info-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
	position: sticky;
	top: 0;
	z-index: 100;
}

.back-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	font-size: 36rpx;
	color: #333;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.edit-btn {
	padding: 10rpx 20rpx;
}

.edit-text {
	font-size: 28rpx;
	color: #007aff;
}

.content {
	padding: 30rpx;
}

.avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 40rpx;
	padding: 40rpx;
	background-color: #fff;
	border-radius: 20rpx;
}

.avatar-tip {
	font-size: 24rpx;
	color: #999;
	margin-top: 20rpx;
}

.info-section {
	background-color: #fff;
	border-radius: 20rpx;
	overflow: hidden;
}

.info-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
	border-bottom: none;
}

.label {
	width: 160rpx;
	font-size: 28rpx;
	color: #666;
	flex-shrink: 0;
}

.value {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	text-align: right;
}

.input-field {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	text-align: right;
	padding: 0;
	border: none;
	background: transparent;
}

.picker-field {
	flex: 1;
	text-align: right;
}

.picker-text {
	font-size: 28rpx;
	color: #333;
}

.action-buttons {
	display: flex;
	padding: 30rpx;
	gap: 20rpx;
}

.cancel-btn, .save-btn {
	flex: 1;
	height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
	border: none;
}

.cancel-btn {
	background-color: #f5f5f5;
	color: #666;
}

.save-btn {
	background-color: #007aff;
	color: #fff;
}

.save-btn:disabled {
	background-color: #ccc;
	color: #999;
}
</style>
